from flask import jsonify, request
from ..models.complaint import Complaint
from ..models.user import User
from ..extensions import db
from ..utils.response import pagination, error, success

# 创建投诉记录
def create_complaint():
    try:
        data = request.json
        
        # 验证必填字段
        if not data.get('user_id') or not data.get('content') or not data.get('images'):
            return error('用户ID、投诉内容和图片为必填字段', 400)
        
        # 验证用户是否存在
        user = User.query.get(data['user_id'])
        if not user:
            return error('投诉用户不存在', 400) 
        
        # 处理图片字段：将列表转换为逗号分隔的字符串
        images_str = ''
        if isinstance(data['images'], list):
            images_str = ','.join(data['images'])
        else:
            # 如果不是列表，直接使用（可能是单个图片字符串）
            images_str = str(data['images'])
        
        # 创建投诉实例
        complaint = Complaint(
            user_id=data['user_id'],
            content=data['content'],
            images=images_str,
            # complaint_time 默认使用当前时间，也可以从请求中获取
            complaint_time=data.get('complaint_time') or None
        )
        
        db.session.add(complaint)
        db.session.commit()
        
        return success({"complaint": complaint.to_dict()}, "投诉记录创建成功")
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)

# 获取投诉列表
from sqlalchemy import text

def get_complaints(data):
    """获取投诉列表，支持按用户ID筛选，按时间筛选，支持分页"""
    try:
        # 构造查询（Complaint + User）
        query = db.session.query(
            Complaint.id,
            Complaint.user_id,
            Complaint.content,
            Complaint.images,
            Complaint.complaint_time,
            Complaint.upvotes,
            Complaint.downvotes,
            User.name.label('user_name')
        ).join(User, Complaint.user_id == User.id)

        # --- 筛选条件 ---
        if data.get('user_id'):
            query = query.filter(Complaint.user_id == data['user_id'])

        if data.get('complaint_time'):
            query = query.filter(Complaint.complaint_time.like(f"%{data['complaint_time']}%"))

        if data.get('content'):
            query = query.filter(Complaint.content.like(f"%{data['content']}%"))

        # --- 统计总数 ---
        total = query.count()

        # --- 排序 ---
        query = query.order_by(Complaint.complaint_time.desc())

        # --- 分页 ---
        page = int(data.get('page', 1))
        page_size = int(data.get('page_size', 10))
        if page < 1:
            page = 1
        if page_size < 1:
            page_size = 10
        elif page_size > 100:
            page_size = 100
        offset = (page - 1) * page_size

        # --- 查询数据 ---
        rows = query.offset(offset).limit(page_size).all()

        # SQLAlchemy 2.x 的 row 对象可用 ._mapping 转 dict
        complaints = [dict(row._mapping) for row in rows]

        # --- 返回结果 ---
        return pagination(
            items=complaints,
            total=total,
            msg='获取成功',
            code=200
        )

    except Exception as e:
        print(f"Error in get_complaints: {str(e)}")
        return error('获取失败', 500)


# 获取单个投诉记录
def get_complaint():
    try:
        complaint_id = request.args.get('id')
        
        if not complaint_id:
            return jsonify({'error': '未提供投诉ID'}), 400
        
        complaint = Complaint.query.get(complaint_id)
        
        if not complaint:
            return jsonify({'error': '投诉记录不存在'}), 404
        
        return success({"complaint": complaint.to_dict()}, "投诉记录获取成功")
    except Exception as e:
        return error(str(e), 500)

# 更新投诉记录
def update_complaint():
    try:
        data = request.json
        complaint_id = data.get('id')
        
        if not complaint_id:
            return error('未提供投诉ID', 400)
        
        complaint = Complaint.query.get(complaint_id)
        
        if not complaint:
            return error('投诉记录不存在', 404)
        
        # 更新字段
        if 'content' in data:
            complaint.content = data['content']
        if 'images' in data:
            # 处理图片字段：将列表转换为逗号分隔的字符串
            if isinstance(data['images'], list):
                complaint.images = ','.join(data['images'])
            else:
                complaint.images = str(data['images'])
        if 'complaint_time' in data:
            complaint.complaint_time = data['complaint_time']
        if 'upvotes' in data:
            complaint.upvotes = data['upvotes']
        if 'downvotes' in data:
            complaint.downvotes = data['downvotes']
        # user_id 不允许修改，保持数据一致性
        
        db.session.commit()
        
        return success({"complaint": complaint.to_dict()}, "投诉记录更新成功")
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)

# 删除投诉记录
def delete_complaint(data):
    try:
        complaint_id = data.get('id')
        
        if not complaint_id:
            return error('未提供投诉ID', 400)
        
        complaint = Complaint.query.get(complaint_id)
        
        if not complaint:
            return error('投诉记录不存在', 404)
        
        db.session.delete(complaint)
        db.session.commit()
        
        return success({"complaint": complaint.to_dict()}, "投诉记录删除成功")
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)       

# 点赞投诉
def upvote_complaint():
    try:
        data = request.json
        complaint_id = data.get('id')
        
        if not complaint_id:
            return error('未提供投诉ID', 400)
        
        complaint = Complaint.query.get(complaint_id)

        if not complaint:
            return error('投诉记录不存在', 404) 
        
        # 增加点赞数
        complaint.upvotes += 1
        db.session.commit()
        
        return success({
            'upvotes': complaint.upvotes,
            'downvotes': complaint.downvotes
        }, "点赞成功")
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)

# 点踩投诉
def downvote_complaint():
    try:
        data = request.json
        complaint_id = data.get('id')
        
        if not complaint_id:
            return error('未提供投诉ID', 400)
        
        complaint = Complaint.query.get(complaint_id)
        
        if not complaint:
            return error('投诉记录不存在', 404)
        
        # 增加点踩数
        complaint.downvotes += 1
        db.session.commit()
        
        return success({
            'upvotes': complaint.upvotes,
            'downvotes': complaint.downvotes
        }, "点踩成功")
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)
